<template>
  <!-- 主容器 -->
  <section class="container">
    <section class="bg"></section>
    <section class="content">
      <!-- 标题 -->
      <section  class="title">
          <span >{{systemTitle}}</span>
      </section>
      <!-- 登录 form 标题 -->
      <section class="login-way">{{$t('login_by_password')}}</section>
      <!-- 登录 form -->
      <section class="login-form">
        <Form :model="loginInfo" @keydown.enter.native="handleSubmit">
          <Input type="text" v-model="loginInfo.loginName" class="login-form-input" size="large" prefix="ios-person" :placeholder="$t('user_code_input')" />
          <Input type="password" v-model="loginInfo.password" on-enter="handleSubmit" class="login-form-input" size="large" prefix="md-lock" :placeholder="$t('user_password_input')" />
          <FormItem>
            <div style="display: flex;align-items: center;margin-top: 10px">
              <Input style="width: 80px" v-model="loginInfo.verifyCode" :placeholder="$t('security_code')" ></Input>
              <div><img ref="verifyCodeImg" src="" left="10" style="margin-left: 10px;margin-right: 3px;margin-top:8px;height:36px;width:200px"/></div>
              <Button icon="md-refresh" :title="$t('refresh')" @click="refreshVerifyCode"></Button>
            </div>
          </FormItem>
          <FormItem>
            <Select v-model="locale"
                    :placeholder="$t('language_switch')"
                    @on-change="onLangChange">
              <Option v-for="item in h5.langs" :disabled="item.disabled" :value="item.lang" :key="item.lang">{{ item.name }}</Option>
            </Select>
          </FormItem>
          <Button :loading="loading" class="login-form-btn-submit" @click="handleSubmit" on-enter="handleSubmit" type="primary">
            {{$t('login')}}</Button>
        </Form>
      </section>
    </section>
    <!-- 版本 -->
    <footer class="footer">
      <div style="width: 100%;display: flex;flex-direction: column">
        {{ $t('browser_recommendation') }}
        <span v-if="locale==='zh-CN'">粤ICP备19150811号-2</span>
      </div>
<!--      浏览器推荐：Chrome 72+ 最佳分辨率：1920*1080 Copyright &copy;2023-->
    </footer>
  </section>
</template>

<script>
import config from '@/config'
import './Login.less'
import { findAll } from '@/api/sysconfig'
import { getVerifyCode } from '@/api/login'
import {mapActions, mapMutations} from "vuex";
import {apiResult, getToken, localRead} from "@/libs/util";
import Vue from "vue";
import MapToolsData from "@/view/Home/map/maptools/data/MapToolsData";
export default {
  name: 'Login',
  watch:{
    locale(n,o){
      if (!!this.sysConfig)
        this.changeTitle(this.sysConfig);
/*      if (n === 'en-US' && !!this.sysConfig.CUSTOMER_TITLE_ES){
        this.systemTitle = this.sysConfig.CUSTOMER_TITLE_ES;
      }else{
        this.systemTitle = this.sysConfig.CUSTOMER_TITLE;
      }*/
    },
/*    sysConfig:{
      handler(n,o) {
        if (!!n){
          this.changeTitle(n);
        }
      }
    },*/
  },
  computed:{
    h5(){
      return{
        languageSwitch: this.$t('language_switch'),
        langs:[
          {lang:'en-US',name:'English',disabled:false},
          {lang:'zh-CN',name:'中文简体' ,disabled:false},
          {lang:'zh-TW',name:'中文繁体',disabled:false},
        ],
      }
    },
/*    sysConfig(){
      const sc = this.$store.getters.sysConfig
      if (!!sc){
        this.changeTitle(sc);
      }
      return sc;
    },*/
  },
  data () {
    return {
      loading: false,
      title: config.title,
      loginInfo: {
        loginName: '',
        password: '',
        verifyCode: '',
        sessionId: ''
      },
      sysConfig:{
        MAP_CENTER_POSITION: null, //地图中心点
        MAP_MODE: 'ONLINE', //在线/离线  ONLINE,OFFLINE
        MAP_LEVEL: null,
        MAP_COORD_INFO: null,
        CUSTOMER_LOGO: null,
        CUSTOMER_TITLE: "",
        CUSTOMER_TITLE_ES:""
      },
      expire:0,
      uuid:null,
      locale: '', //这里不能设默认值，否则.......
      systemTitle:null,
      mapVendor:[]

    }

  },
  methods: {
    ...mapMutations([
      'setSysConfig','setDeviceStatus','setLocal','setMediaReplayFinish'
    ]),
    ...mapActions([
      'pushUserMessage',
      'emptyUserMessage'
    ]),
    onLangChange(lang){
      //console.log("Lonin.onlangChange this.$i18n.locale=%o",this.$i18n.locale)
      //console.log("Lonin.onlangChange this.locale=%o",this.locale)
      this.$i18n.locale = this.locale;
      //保存到本地
      this.setLocal(this.locale);
      this.h5.langs.forEach((item)=>{
        item.disabled = false;
        if (item.lang === this.locale){
          item.disabled = true;
        }
      })
      config.lang = this.locale;
    },
    setThisLocale(lang){
      console.log(lang);
      this.$i18n.locale = lang;
      this.locale = lang;
    },

    handleSubmit () {
      //执行登录
      //console.log("loginInfo: %o",this.loginInfo);
      const _this = this;
      if (!this.loginInfo.loginName) {
        this.$Message.error(this.$t('empty_user_code'))
      } else  if (!this.loginInfo.password) {
        this.$Message.error(this.$t('empty_password'))
      }else if (!this.loginInfo.verifyCode && process.env.NODE_ENV === "production") {
        this.$Message.error(this.$t('empty_security_code'))
      }else{
        this.loading = true;
        this.$store.dispatch('login', this.loginInfo).then((token) => {
          //console.log("登录成功，转到了 '/'的routers ");
            this.sse(token).then(eventSource=>{
              //sessionStorage.setItem('SSE-EVENT',eventSource);
              this.$router.push({ path: '/' })
            }).catch(err=>{
              this.$router.push({ path: '/' })
            });
        }).catch(err => {
          console.log(err)
          if (!!err.code){
            this.$Message.error(this.$t("msg_"+err.code))
            if (err.code === 100000){
              //this.$Message.error(this.$t("msg_"+err.code))
              this.$Message.error(err.msg);
            }
          }

        })
      }
      this.loading = false;

    },
    /**
     * 刷新验证码
     */
    refreshVerifyCode(){
      //验证码
      getVerifyCode().then((res)=>{
          apiResult(res.data,false,result=>{
            this.expire = result.data.expireSec;
            this.loginInfo.sessionId = result.data.uuid;
            this.$refs.verifyCodeImg.src = result.data.image;
          })
      });
    },

    sse(token){
      const that = this;
      //console.log("申请SSE推送API调用，客户端ID: %o, token: %o ",that.$browserId,token);
      return new Promise((resolve, reject) => {
        //console.log("申请SSE推送API调用，客户端ID: " + that.$browserId);
        let baseUrl = process.env.NODE_ENV === 'development' ? that.$config.sseUrl.dev() : that.$config.sseUrl.pro()
        if (baseUrl[baseUrl.length-1] !== "/") baseUrl = baseUrl + "/";
        const browserId = sessionStorage.getItem("browse_id")
        if (!browserId){
          reject(">>>>>> none browse Id")
          return;
        }
        const eventSource = new EventSource(baseUrl+'sse/emit?clientId=' + browserId + "&token=" + token);
        if (!!eventSource){
          eventSource.removeEventListener('open', null);
          eventSource.removeEventListener('message', null);
          eventSource.removeEventListener('error', null);
        }
        //if (!(!!this.$eventSource)){
          console.log("sse重新连接是为了更新 token而已");
          /** messge 事件 */
          eventSource.addEventListener('message', function(evt) {
            console.log("SSE 收到信息：%o",evt.data);
            //that.$Message.info("SSE 收到信息");
            const data = JSON.parse(evt.data);
            if (data.code === 0){
              if (data.data != null){
                if (data.data.type === 'ALARM_NOTIFY'){
                  //报警数据
                  that.pushUserMessage(data.data);
                }else if (data.data.type === 'UP_DOWN_LINE_NOTIFY'){
                  console.log("保存设备上下线状态信息：%o", data.data.object)
                  //设备上下线
                  that.setDeviceStatus(data.data.object)
                }else if (data.data.type === 'MEDIA_REPLAY_FINISHED'){
                  console.log("保存录像回放结束信息：%o", data.data.object)
                  //回放结束
                  that.setMediaReplayFinish(data.data.object)
                }else if (data.data.type === 'MEDIA_DOWNLOAD_FINISHED'){
                  console.log("保存录像下载结束信息：%o", data.data.object)
                  //录像结束
                }

              }
            }else{
              that.$Message.error(data.msg);
            }
          });

          /** open 事件 */
          eventSource.addEventListener('open', function(e) {
            console.log("SSE连接打开.");
            //that.$Message.info("SSE连接打开.");
          }, false);

          /** error 事件 */
          eventSource.addEventListener('error', function(e) {
            if (e.target.readyState == EventSource.CLOSED) {
              console.log("SSE连接关闭, n秒后重连...... ");
            } else {
              console.log("SSE 错误：%o",e.target.readyState);
            }
          }, false);
        //}
        resolve(eventSource);
      })
    },

    changeTitle(sc){
      //console.log("login.changeTitle locale=%o,sysConfig=%o",this.locale,sc)
      if (this.locale === 'en-US' && !!sc.CUSTOMER_TITLE_ES){
        this.systemTitle = sc.CUSTOMER_TITLE_ES;
      }else if (!!sc.CUSTOMER_TITLE){
        this.systemTitle = sc.CUSTOMER_TITLE;
      }
    }
  },
  mounted() {
    //多语言选择
    //上次有没有设置
/*
    let lang=localRead('local')
    const navLang = navigator.language //var m = navigator.language
    console.log("到英文浏览器就报错，navLang: %o",navLang)
    const localLang = (navLang === 'zh-CN' || navLang === 'en-US') ? navLang : false
    console.log("到英文浏览器就报错，localLang: %o",localLang)
    console.log("到英文浏览器就报错，localRead: %o",localRead)
    let lang = localLang || localRead('local') || 'zh-CN'
*/
    //adapter.browserDetails.browser

    //console.log("这个为什么报错，localRead: %o",localRead)
    this.refreshVerifyCode();
    //系统参数
    findAll().then(res => {
      apiResult(res.data,false,result=>{
        //console.log("login.mouted,sysConfig=%o",this.sysConfig);
        this.sysConfig = result.data;
        this.setSysConfig(result.data);
        this.changeTitle(this.sysConfig);
      })
    })

/*    if (!!this.$config.eventSource){
      console.log(">>>>>>>> 关闭SSE连接: id=%o",this.$browserId);
      this.$config.eventSource.removeEventListener('open', null);
      this.$config.eventSource.removeEventListener('message', null);
      this.$config.eventSource.removeEventListener('error', null);
      this.$config.eventSource.close();
      this.$config.eventSource = null;
    }*/

    //默认语言
    let local = this.$store.state.app.local;
    console.log(">>>>>> Longin.local: %o",local)
    if (!local){
      const navLang = navigator.language;
      console.log(">>>>>> Longin.navLang-2: %o",navLang.substring(0,2))
      if (!!navLang){
        if (navLang.substring(0,2) === 'en'){
          local = "en-US";
        }else{
          local = navLang;
        }
      }else{
        local = "en-US";
      }
    }
    let found = false;
    this.h5.langs.forEach(item=>{
      if (item.lang === local){
        found = true;
      }
    })
    if (!found){
      local = 'en-US'
    }
    this.setThisLocale(local)

    this.$nextTick(()=>{

    })
    //console.log("*********>>>> livePlayer=%o",config.livePlayer());
  }
}
</script>

<style scoped>

</style>
